<template>
  <div class="form-box">
    <el-form :model="form" :rules="formRules" ref="refForm" label-width="115px">
      <!-- 参与条件 -->
      <el-form-item
        label="参与条件"
        prop="conditionData.conditionOfParticipation.conditionType"
      >
        <el-select
          v-model="form.conditionData.conditionOfParticipation.conditionType"
          @change="changeConditionType"
          style="width:10%"
        >
          <el-option
            :label="item.dictLabel"
            :value="item.dictValue"
            v-for="(item, index) of partakeConditionList"
            :key="index"
          ></el-option>
        </el-select>
        <!-- 试听 -->
        <span
          v-if="
            form.conditionData.conditionOfParticipation.conditionType ===
              'AUDITION'
          "
        >
          至少
          <el-input-number
            v-model="
              form.conditionData.conditionOfParticipation
                .conditionOfAuditionData.configDuration
            "
            placeholder="试听时长"
            :controls="false"
            :precision="0"
            :min="1"
            :max="100"
            style="width:10%; margin-right:10px"
          ></el-input-number>
          <el-select
            v-model="
              form.conditionData.conditionOfParticipation
                .conditionOfAuditionData.unit
            "
            style="width:10%"
          >
            <el-option
              :label="item.dictLabel"
              :value="item.dictValue"
              v-for="(item, index) of unitTypeList"
              :key="index"
            ></el-option>
          </el-select>
        </span>
        <!-- 看课 -->
        <span
          v-if="
            form.conditionData.conditionOfParticipation.conditionType ===
              'WATCH'
          "
        >
          至少
          <el-input-number
            v-model="
              form.conditionData.conditionOfParticipation.conditionOfWatchData
                .configDuration
            "
            placeholder="听课时长"
            :controls="false"
            :precision="0"
            :min="1"
            :max="100"
            style="width:10%;margin-right:10px"
          ></el-input-number>
          <el-select
            v-model="
              form.conditionData.conditionOfParticipation.conditionOfWatchData
                .unit
            "
            style="width:10%"
          >
            <el-option
              :label="item.dictLabel"
              :value="item.dictValue"
              v-for="(item, index) of unitTypeList"
              :key="index"
            ></el-option>
          </el-select>
        </span>
        <!-- 提交作业 -->
        <span
          v-if="
            form.conditionData.conditionOfParticipation.conditionType ===
              'SUBMITTING_ASSIGNMENTS'
          "
        >
          至少
          <el-input-number
            v-model="
              form.conditionData.conditionOfParticipation
                .conditionOfSubmitAssignmentData.assignmentCount
            "
            placeholder="提交作业份数"
            :controls="false"
            :precision="0"
            :min="1"
            :max="100"
            style="width:10%"
          ></el-input-number>
          <span class="partakeType-item__tip">（份数）</span>
        </span>
      </el-form-item>
      <!-- 参与课程 -->
      <el-form-item
        label="参与课程"
        v-if="showCourseRange"
        prop="conditionData.conditionOfParticipation.courseRange"
      >
        <el-select
          v-model="form.conditionData.conditionOfParticipation.courseRange"
          placeholder="请选择课程类型"
          @change="changeCourseRange"
          style="width:15%"
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) of courseRangeTypeList"
            :key="index"
          ></el-option>
        </el-select>
        <el-button
          v-if="showCourseList"
          icon="el-icon-plus"
          type="success"
          style="margin-left:10px"
          @click="handleChoose('COURSE')"
          >选择课程</el-button
        >
      </el-form-item>
      <!-- 课程列表 -->
      <courseTable
        v-if="showCourseList && showCourseRange"
        :courseData="courseDialogData.courseList"
        @deleteCourse="deleteCourse"
        style="margin-left:75px"
      />
      <el-form-item label="赠送商品" prop="giftedCourses">
        <el-button
          icon="el-icon-plus"
          class="form-item__action"
          type="success"
          @click="handleChoose('GOODS')"
          >选择商品</el-button
        >
      </el-form-item>
      <!-- 商品列表 -->
      <goodsTable
        :goodsData="goodsDialogData.goodsList"
        style="margin-left:75px"
        @deleteGoods="deleteGoods"
      />
      <el-form-item
        label="活动凭证(图)"
        prop="activityVoucher.activityVoucherImages"
      >
        <uploadImg
          ref="clsImg"
          :img-array="form.activityVoucher.activityVoucherImages"
          :accept="'.jpg,.png'"
          :max-size="5"
          :preview-img="false"
          :single-file="45"
          @setImgInfo="setImgInfo"
        ></uploadImg>
      </el-form-item>
      <el-form-item
        label="活动凭证(文)"
        prop="activityVoucher.activityVoucherDescription"
      >
        <el-input
          type="textarea"
          :rows="5"
          show-word-limit
          maxlength="2000"
          placeholder="请输入不超过2000字内容"
          v-model="form.activityVoucher.activityVoucherDescription"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <div class="handlerButton">
      <el-button type="success" @click="handelTab('generalConfig')">
        上一步
      </el-button>
      <el-button type="info" @click="cancel">取 消</el-button>
      <el-button type="success" @click="handelTab('userRules')">
        下一步
      </el-button>
    </div>
    <!-- 选择课程弹窗 -->
    <chooseCourseDialog
      v-if="courseDialogData.isShow"
      :courseType="courseType"
      :dialog-data="courseDialogData"
      @setCourseList="setCourseList"
    />
    <!-- 选择商品弹窗 -->
    <chooseGoodsDialog
      v-if="goodsDialogData.isShow"
      :dialog-data="goodsDialogData"
      @setGoodsList="setGoodsList"
    />
  </div>
</template>

<script>
import { sysNormalDisable } from '@utils/dictionariesFunc'
import uploadImg from '@common/uploadImg' // 上传图片公共组件
import chooseCourseDialog from '../components/chooseCourseDialog'
import chooseGoodsDialog from '../components/chooseGoodsDialog'
import courseTable from '../components/courseTable'
import goodsTable from '../components/goodsTable'
const defaultAuditionData = {
  courseRange: null, //赠课活动试听条件课程范围
  configDuration: 1, //赠课活动试听条件试听时长
  specifyCourseIds: [], //赠课活动试听条件指定课程Ids
  unit: 'MINUTES'
}
const defaultSubmitAssignmentData = {
  assignmentCount: 1, //提交作业数
  courseRange: null, //课程范围
  specifyCourseIds: [] //课程Ids
}
const defaultWatchData = {
  courseRange: null, //看课条件课程范围
  configDuration: 1, //看课时长
  specifyCourseIds: [], //课程Ids
  unit: 'MINUTES' //看课时长单位
}
export default {
  props: ['activityInfo'],
  components: {
    uploadImg,
    courseTable,
    goodsTable,
    chooseCourseDialog,
    chooseGoodsDialog
  },
  data() {
    const _this = this
    return {
      // 传给选择商品弹窗 判断如果为试听的话 把参数VIP改为TRIAL
      courseType: '',
      userGroupingData: false, // 分组列表展示与隐藏
      courseList: [], // 分组列表
      goodsList: {}, // 点开分组列表回显
      // 课程弹窗数据
      courseDialogData: {
        isShow: false,
        courseList: []
      },
      // 商品弹窗数据
      goodsDialogData: {
        isShow: false,
        goodsList: []
      },
      form: {
        //赠课活动凭证配置
        activityVoucher: {
          activityVoucherDescription: '',
          activityVoucherImages: []
        },
        //赠课活动条件配置数据
        conditionData: {
          //赠课活动试听条件配置数据
          conditionOfParticipation: {
            conditionOfAuditionData: {
              courseRange: '', //赠课活动试听条件课程范围
              configDuration: 1, //赠课活动试听条件试听时长
              specifyCourseIds: [], //赠课活动试听条件指定课程Ids
              unit: 'MINUTES'
            },
            //赠课活动看课条件配置数据
            conditionOfWatchData: {
              courseRange: '', //看课条件课程范围
              configDuration: 1, //看课时长
              specifyCourseIds: [], //课程Ids
              unit: 'MINUTES' //看课时长单位
            },
            //赠课活动提交作业条件配置数据
            conditionOfSubmitAssignmentData: {
              assignmentCount: 1, //提交作业数
              courseRange: '', //课程范围
              specifyCourseIds: [] //课程Ids
            },
            conditionType: '', //条件类型
            courseRange: 'ALL'
          }
        },
        //活动赠课
        giftedCourses: []
      },
      formRules: {
        'conditionData.conditionOfParticipation.conditionType': [
          {
            required: true,
            message: '请选择参与条件',
            trigger: 'change'
          }
        ],
        'conditionData.conditionOfParticipation.courseRange': [
          {
            required: true,
            message: '请选择参与课程',
            trigger: 'change'
          }
        ],
        'activityVoucher.activityVoucherImages': {
          validator: _this.checkActivityVoucherImages,
          trigger: 'change'
        },
        'activityVoucher.activityVoucherDescription': {
          validator: _this.checkActivityVoucherDescription,
          trigger: 'blur'
        },
        giftedCourses: {
          validator: _this.checkGiftedCourses,
          trigger: 'blur'
        },
        courseList: {
          validator: _this.checkGrouping,
          trigger: 'blur'
        }
      },
      // 课程类型参与条件
      courseTypeList: [
        { label: '全部课程', value: 'ALL' },
        { label: '指定课程', value: 'SPECIFY' }
      ],
      // 试听的参与课程
      auditionTypeList: [
        { label: '全部试听课程', value: 'ALL' },
        { label: '指定试听课程', value: 'SPECIFY' }
      ],
      // 参与条件
      partakeConditionList: [],
      // 时间单位
      unitTypeList: [],
      // 发放用户
      userRangeTypeList: [{ dictLabel: '选择发放用户', dictValue: '' }],
      userParticipateList: [{ dictLabel: '选择参与用户', dictValue: '' }],
      groupId: []
    }
  },
  computed: {
    showCourseRange() {
      if (
        this.form.conditionData.conditionOfParticipation.conditionType === '' ||
        this.form.conditionData.conditionOfParticipation.conditionType ===
          'GIFT'
      ) {
        return false
      } else {
        return true
      }
    },
    // 显示选择课程、课程列表
    showCourseList() {
      if (
        this.form.conditionData.conditionOfParticipation.courseRange === 'ALL'
      ) {
        return false
      } else {
        return true
      }
    },
    courseRangeTypeList() {
      let rangeTypeList = null
      switch (this.form.conditionData.conditionOfParticipation.conditionType) {
        case 'AUDITION':
          rangeTypeList = this.auditionTypeList
          break
        case 'WATCH':
        case 'SUBMITTING_ASSIGNMENTS':
          rangeTypeList = this.courseTypeList
          break
        default:
          break
      }
      return rangeTypeList
    }
  },
  async mounted() {
    let [
      userRangeTypeData,
      conditionTypeData,
      timeTypeData
    ] = await Promise.all([
      sysNormalDisable(
        'activity_course_user_type',
        'activity_course_user_type'
      ),
      sysNormalDisable('giving_condition_type', 'giving_condition_type'),
      sysNormalDisable('giving_course_time_type', 'giving_course_time_type'),
      sysNormalDisable('goods_type', 'goods_type')
    ])
    this.userRangeTypeList = [...this.userRangeTypeList, ...userRangeTypeData]
    this.userParticipateList = [
      ...this.userParticipateList,
      ...userRangeTypeData
    ]

    this.partakeConditionList = conditionTypeData
    this.unitTypeList = timeTypeData
  },
  watch: {
    'goodsDialogData.goodsList': {
      handler(newV, oldV) {
        this.form.giftedCourses = newV
        if (newV.length > 0) {
          this.$refs['refForm'].clearValidate('giftedCourses')
        }
      },
      deep: 'true'
    },
    activityInfo: {
      handler(val) {
        this.form = this.activityInfo
        this.form.conditionData.conditionOfParticipation.courseRange = this.convertUserRange(
          this.form.conditionData
        )
        this.courseDialogData.courseList = this.form.givingCourseInfosResourceList
        this.goodsDialogData.goodsList = this.form.coursesGoodsDtoList
      },
      deep: true
    }
  },
  methods: {
    /* 上一步 */
    handelTab(name) {
      this.$emit('handleClick', { name })
    },
    /* 取消 */
    cancel() {
      this.$router.push({ name: 'wh:inviteHaveGift' })
    },
    // 校验是否存在上传图片或者描述
    checkActivityVoucherImages(rule, value, callback) {
      if (
        value.length === 0 &&
        !this.form.activityVoucher.activityVoucherDescription
      ) {
        callback(new Error('请上传活动凭证'))
      } else {
        this.$refs['refForm'].clearValidate(
          'activityVoucher.activityVoucherDescription'
        )
        callback()
      }
    },
    // 校验是否存在上传图片或者描述
    checkActivityVoucherDescription(rule, value, callback) {
      if (
        this.form.activityVoucher.activityVoucherImages.length === 0 &&
        !value
      ) {
        callback(new Error('请输入活动凭证'))
      } else {
        this.$refs['refForm'].clearValidate(
          'activityVoucher.activityVoucherImages'
        )
        callback()
      }
    },
    // 校验赠送商品
    checkGiftedCourses(rule, value, callback) {
      if (value.length === 0) {
        callback(new Error('请选择赠送商品'))
      } else {
        callback()
      }
    },
    // 参与条件改变
    changeConditionType(val) {
      // 设置类型改为默认值
      const res = this.partakeConditionList.filter((item) => {
        return item.dictValue == val
      })
      if (res[0].dictValue == val) {
        this.courseDialogData.courseList = []
        this.goodsDialogData.goodsList = []
        this.form.conditionData.conditionOfParticipation.courseRange = ''
        this.form.activityVoucher.activityVoucherDescription = ''
        // 清除图片
        this.$refs.clsImg.clearList()
      }
      switch (val) {
        case 'AUDITION':
          this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData = {
            ...defaultSubmitAssignmentData
          }
          this.form.conditionData.conditionOfParticipation.conditionOfWatchData = {
            ...defaultWatchData
          }
          break
        case 'WATCH':
          this.form.conditionData.conditionOfParticipation.conditionOfAuditionData = {
            ...defaultAuditionData
          }
          this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData = {
            ...defaultSubmitAssignmentData
          }
          break
        case 'SUBMITTING_ASSIGNMENTS':
          this.form.conditionData.conditionOfParticipation.conditionOfAuditionData = {
            ...defaultAuditionData
          }
          this.form.conditionData.conditionOfParticipation.conditionOfWatchData = {
            ...defaultWatchData
          }
          break
        case 'GIFT':
          this.form.conditionData.conditionOfParticipation.conditionOfAuditionData = {
            ...defaultAuditionData
          }
          this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData = {
            ...defaultSubmitAssignmentData
          }
          this.form.conditionData.conditionOfParticipation.conditionOfWatchData = {
            ...defaultWatchData
          }
          break
        default:
          break
      }
      this.clearCourseList()
    },
    // 切换选择课程类型
    changeCourseRange(val) {
      switch (this.form.conditionData.conditionOfParticipation.conditionType) {
        case 'AUDITION':
          this.form.conditionData.conditionOfParticipation.conditionOfAuditionData.courseRange = val
          break
        case 'WATCH':
          this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData.courseRange = val
          break
        case 'SUBMITTING_ASSIGNMENTS':
          this.form.conditionData.conditionOfParticipation.conditionOfWatchData.courseRange = val
          break
        default:
          break
      }
      this.clearCourseList()
    },
    // 设置添加按钮事件（课程、商品）
    handleChoose(type) {
      switch (type) {
        case 'COURSE':
          // 传参当为试听的时候 调用另一个参数接口
          this.courseType = this.form.conditionData.conditionOfParticipation.conditionType
          this.courseDialogData.isShow = true
          break
        case 'GOODS':
          this.goodsDialogData.isShow = true
          break
        case 'USERTYPE':
          this.userGroupingData = true
          break
        default:
          break
      }
    },
    // 设置课程选中的数据
    setCourseList(courseList) {
      this.courseDialogData.courseList = courseList
    },
    // 设置商品选中的数据
    setGoodsList(goodsList) {
      this.goodsDialogData.goodsList = goodsList
    },
    // 删除课程
    deleteCourse(index) {
      this.courseDialogData.courseList.splice(index, 1)
    },
    // 删除商品
    deleteGoods(index) {
      this.goodsDialogData.goodsList.splice(index, 1)
    },
    // 上传图片返回数据
    setImgInfo(val) {
      if (val) {
        this.form.activityVoucher.activityVoucherImages = val.map((item) => {
          if (item.url) return item.url
          else return item
        })
      }
    },
    // 清空选择课程
    clearCourseList() {
      this.courseDialogData.courseList = []
    },
    // 清空选择商品
    clearGoodsList() {
      this.goodsDialogData.goodsList = []
    },
    // 转换参与条件类型
    convertUserRange(conditionData) {
      let courseRange = 'ALL'
      switch (conditionData.conditionOfParticipation.conditionType) {
        case 'AUDITION':
          courseRange =
            conditionData.conditionOfParticipation.conditionOfAuditionData
              .courseRange
          break
        case 'WATCH':
          courseRange =
            conditionData.conditionOfParticipation.conditionOfWatchData
              .courseRange
          break
        case 'SUBMITTING_ASSIGNMENTS':
          courseRange =
            conditionData.conditionOfParticipation
              .conditionOfSubmitAssignmentData.courseRange
          break
        default:
          break
      }
      return courseRange
    },
    // 表单提交
    collectData() {
      let obj = Object.assign({}, this.form)
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          const courseRange = this.form.conditionData.conditionOfParticipation
            .courseRange
          let specifyCourseIds = []
          if (courseRange !== 'ALL') {
            specifyCourseIds = this.courseDialogData.courseList.map((item) => {
              return item.id
            })
          }
          switch (
            this.form.conditionData.conditionOfParticipation.conditionType
          ) {
            case 'AUDITION':
              this.form.conditionData.conditionOfParticipation.conditionOfAuditionData.specifyCourseIds = specifyCourseIds
              this.form.conditionData.conditionOfParticipation.conditionOfAuditionData.courseRange = courseRange
              break
            case 'WATCH':
              this.form.conditionData.conditionOfParticipation.conditionOfWatchData.specifyCourseIds = specifyCourseIds
              this.form.conditionData.conditionOfParticipation.conditionOfWatchData.courseRange = courseRange
              break
            case 'SUBMITTING_ASSIGNMENTS':
              this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData.specifyCourseIds = specifyCourseIds
              this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData.courseRange = courseRange
              break
            default:
              break
          }
          this.form.giftedCourses = this.goodsDialogData.goodsList
        } else obj = { tab: 'customConfig' }
      })
      return obj
    }
  }
}
</script>

<style lang="less" scoped>
.handlerButton {
  width: 292px;
  margin: 0 auto;
  .el-button {
    margin-right: 30px;
  }
}
</style>
